package com.tianze.library.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.tianze.library.R;
import com.tianze.library.listener.SingleClickListener;
import com.tianze.library.utils.DialogUtils;
import com.tianze.library.utils.KeyBoardUtils;
import com.tianze.library.utils.ToastUtils;
import com.tianze.library.view.SimpleDialog;
import com.tianze.library.view.UpdateDialog;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import icepick.Icepick;

/**
 * Created by mapple.
 */
public class BaseActivity extends AppCompatActivity {

    protected Activity mActivity;
    protected Toolbar mToolbar;
    protected ActionBar mActionBar;
    protected LayoutInflater mInflater;
    private TextView tvLeft;
    private TextView tvRight;
    private TextView tvTitle;
    private ImageView ivLeft;
    private ImageView ivRight;

    private SimpleDialog mWaitingDialog;

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Icepick.saveInstanceState(this, outState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Icepick.restoreInstanceState(this, savedInstanceState);
        if (getLayoutId() != 0) {
            setContentView(getLayoutId());
            mToolbar = ButterKnife.findById(this, R.id.toolbar);
        }
        mActivity = this;
        mInflater = getLayoutInflater();
        onAfterSetContentLayout();
        initToolbar(mToolbar);
        init(savedInstanceState);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedCheck) {
            checkPermissions(needPermissions);
        }
    }

    @Override
    protected void onDestroy() {
        hideWaitingDialog();
        OkHttpUtils.getInstance().cancelTag(this);
        mActionBar = null;
        mToolbar = null;
        super.onDestroy();
    }

    protected int getActionBarSize() {
        TypedValue typedValue = new TypedValue();
        int[] textSizeAttr = new int[]{R.attr.actionBarSize};
        int indexOfAttrTextSize = 0;
        TypedArray a = obtainStyledAttributes(typedValue.data, textSizeAttr);
        int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
        a.recycle();
        return actionBarSize;
    }

    protected void init(Bundle savedInstanceState) {
    }

    protected void initToolbar(Toolbar toolbar) {
        if (null == toolbar) return;
        toolbar.setContentInsetsAbsolute(16, 16);
        toolbar.setPadding(0, 0, 0, 0);// 平板
        setSupportActionBar(toolbar);
        mActionBar = getSupportActionBar();
        int customToolbar = getToolbarCustomView();
        if (0 != customToolbar) {
            View view = inflateView(customToolbar);
            Toolbar.LayoutParams params = new Toolbar.LayoutParams(
                    ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
            mToolbar.addView(view, params);
            tvTitle = (TextView) view.findViewById(R.id.custom_title);
            tvLeft = (TextView) view.findViewById(R.id.tv_left);
            tvRight = (TextView) view.findViewById(R.id.tv_right);

            tvTitle.setTextColor(getTextColor());
            tvLeft.setTextColor(getTextColor());
            tvRight.setTextColor(getTextColor());

            ivLeft = (ImageView) view.findViewById(R.id.iv_left);
            ivRight = (ImageView) view.findViewById(R.id.iv_right);
            if (0 != getLeftActionText()) {
                setLeftActionText(getLeftActionText());
                tvLeft.setVisibility(View.VISIBLE);
                ivLeft.setVisibility(View.GONE);
            }
            if (0 != getRightActionText()) {
                setRightActionText(getRightActionText());
                tvRight.setVisibility(View.VISIBLE);
                ivRight.setVisibility(View.GONE);
            }
            if (null != tvLeft) {
                tvLeft.setOnClickListener(new SingleClickListener() {
                    @Override
                    public void onSingleClick(View view) {
                        onLeftAction();
                    }
                });
            }
            if (null != tvRight) {
                tvRight.setOnClickListener(new SingleClickListener() {
                    @Override
                    public void onSingleClick(View v) {
                        onRightAction();
                    }
                });
            }
            if (null != ivLeft) {
                ivLeft.setOnClickListener(new SingleClickListener() {
                    @Override
                    public void onSingleClick(View view) {
                        onLeftAction();
                    }
                });
            }
            if (null != ivRight) {
                ivRight.setOnClickListener(new SingleClickListener() {
                    @Override
                    public void onSingleClick(View v) {
                        onRightAction();
                    }
                });
            }
        }
        if (hasBackButton()) {
            mActionBar.setHomeAsUpIndicator(R.drawable.left);
            //mActionBar.setDisplayHomeAsUpEnabled(true);
            toolbar.setNavigationOnClickListener(new SingleClickListener() {
                @Override
                public void onSingleClick(View v) {
                    onBackPressed();
                }
            });
        }
        setToolbarTitle(getToolbarTitle());
        setToolbarSubTitle(getToolbarSubTitle());
    }

    protected void setToolbarTitle(String title) {
        if (null != tvTitle) {
            tvTitle.setText(title);
        } else if (null != mActionBar) {
            mActionBar.setTitle(title);
        }
    }

    protected void setToolbarTitle(int title) {
        if (0 != title) setToolbarTitle(getString(title));
    }

    protected void setToolbarSubTitle(String title) {
        if (null == tvTitle && null != mActionBar) mActionBar.setSubtitle(title);
    }

    protected void setToolbarSubTitle(int title) {
        if (0 != title) setToolbarSubTitle(getString(title));
    }

    public void setCustomTitle(String title) {
        if (null != tvTitle) {
            tvTitle.setText(title);
        }
    }

    public void setCustomTitle(int title) {
        if (null != tvTitle) {
            tvTitle.setText(title);
        }
    }

    protected void onAfterSetContentLayout() {
        ButterKnife.bind(this);
    }

    protected int getLayoutId() {
        return 0;
    }

    protected int getTextColor() {
        return getResources().getColor(R.color.white);
    }

    protected int getToolbarCustomView() {
        return R.layout.tiza_toolbar_custom_view;
    }

    protected View inflateView(int resId) {
        return mInflater.inflate(resId, null);
    }

    protected int getToolbarTitle() {
        return R.string.app_name;
    }

    protected int getToolbarSubTitle() {
        return 0;
    }

    protected boolean hasBackButton() {
        return false;
    }

    protected void onLeftAction() {
        onBackPressed();
    }

    protected void onRightAction() {

    }

    protected int getLeftActionText() {
        return R.string.back;
    }

    protected int getRightActionText() {
        return 0;
    }

    public void setLeftActionText(@StringRes int res) {
        setLeftActionText(getString(res));
    }

    public void setLeftActionText(@NonNull String res) {
        if (null != tvLeft) {
            tvLeft.setText(res);
            tvLeft.setVisibility(View.VISIBLE);
            ivLeft.setVisibility(View.GONE);
        }
    }

    public void setLeftActionResource(@DrawableRes int res) {
        if (null != ivLeft && 0 != res) {
            ivLeft.setBackgroundResource(res);
            tvLeft.setVisibility(View.GONE);
            ivLeft.setVisibility(View.VISIBLE);
        }
    }

    public void setRightActionText(@StringRes int res) {
        setRightActionText(getString(res));
    }

    public void setRightActionText(@NonNull String res) {
        if (null != tvRight) {
            tvRight.setText(res);
            tvRight.setVisibility(View.VISIBLE);
            ivRight.setVisibility(View.GONE);
        }
    }

    public void setRightActionResource(@DrawableRes int res) {
        if (null != ivRight && 0 != res) {
            ivRight.setBackgroundResource(res);
            tvRight.setVisibility(View.GONE);
            ivRight.setVisibility(View.VISIBLE);
        }
    }

    public void setRightActionListener(OnClickListener ocl) {
        if (null != tvRight) {
            tvRight.setOnClickListener(ocl);
        }
        if (null != ivRight) {
            ivRight.setOnClickListener(ocl);
        }
    }

    public void showLeftTextAction() {
        if (null != tvLeft) {
            tvLeft.setVisibility(View.VISIBLE);
        }
    }

    public void hideLeftTextAction() {
        if (null != tvLeft) {
            tvLeft.setVisibility(View.GONE);
        }
    }

    public void showLeftImageAction() {
        if (null != ivLeft) {
            ivLeft.setVisibility(View.VISIBLE);
        }
    }

    public void hideLeftImageAction() {
        if (null != ivLeft) {
            ivLeft.setVisibility(View.GONE);
        }
    }

    public void showRightTextAction() {
        if (null != tvRight) {
            tvRight.setVisibility(View.VISIBLE);
        }
    }

    public void hideRightTextAction() {
        if (null != tvRight) {
            tvRight.setVisibility(View.GONE);
        }
    }

    public void showRightImageAction() {
        if (null != ivRight) {
            ivRight.setVisibility(View.VISIBLE);
        }
    }

    public void hideRightImageAction() {
        if (null != ivRight) {
            ivRight.setVisibility(View.GONE);
        }
    }

    protected void toast(@NonNull String message) {
        ToastUtils.showShort(getApplicationContext(), message);
    }

    protected void toast(@StringRes int message) {
        toast(getString(message));
    }

    protected void showWaitingDialog() {
        if (null == mWaitingDialog) {
            mWaitingDialog = DialogUtils.getWaitDialog(this);
        }
        if (!isWaitingDialogShowing()) mWaitingDialog.setMessageText("请稍后...").show();
    }

    protected void showWaitingDialog(String title) {
        if (null == mWaitingDialog) {
            mWaitingDialog = DialogUtils.getWaitDialog(this);
        }
        if (isWaitingDialogShowing()) mWaitingDialog.setMessageText(title);
        else mWaitingDialog.setMessageText(title).show();
    }

    protected boolean isWaitingDialogShowing() {
        return null == mWaitingDialog ? false : mWaitingDialog.isShowing();
    }

    protected void hideWaitingDialog() {
        if (null != mWaitingDialog) {
            mWaitingDialog.dismiss();
        }
    }

    protected void showWarnDialog(String title) {
//        DialogUtils.getWarnDialog(this, title).show();
        ToastUtils.showLong(this,title);
    }

    protected void showConfirmDialog(String message, SimpleDialog.OnSimpleClickListener listener) {
        DialogUtils.getConfirmDialog(this, message, listener).show();
    }

    protected void showCustomConfirmDialog(
            String message, String confirm, String cancel,
            SimpleDialog.OnSimpleClickListener confirmListener,
            SimpleDialog.OnSimpleClickListener cancelListener
    ) {
        DialogUtils.getCustomConfirmDialog(this, message, confirm, cancel, cancelListener,
                                           confirmListener
        ).show();
    }

    protected void showUpdateDialog(
            String message, UpdateDialog.OnSimpleClickListener confirmListener,
            UpdateDialog.OnSimpleClickListener cancelListener
    ) {
        DialogUtils.getUpdateDialog(this, message, confirmListener, cancelListener).show();
    }

    protected Context getCurrentContext() {
        return this;
    }

    protected void hideKeyboard() {
        KeyBoardUtils.hideKeyboard(this);
    }

    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {};

    private static final int PERMISSON_REQUESTCODE = 0;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    protected boolean isNeedCheck = false;
    /**
     * 权限验证通过
     */
    protected boolean checkOK = false;

    /**
     * 检查权限
     */
    protected void checkPermissions(String... permissions) {
        List<String> needRequestPermissonList = findDeniedPermissions(permissions);
        if (null != needRequestPermissonList && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(this, needRequestPermissonList.toArray(
                    new String[needRequestPermissonList.size()]), PERMISSON_REQUESTCODE);
        } else {
            permissionOK();
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this,
                                                  perm
            ) != PackageManager.PERMISSION_GRANTED) {
                needRequestPermissonList.add(perm);
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, perm)) {
                    needRequestPermissonList.add(perm);
                }
            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(
            int requestCode, String[] permissions, int[] paramArrayOfInt
    ) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }

    /**
     * 显示提示信息
     */
    private void showMissingPermissionDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);
        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        builder.setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startAppSettings();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 启动应用的设置
     */
    private void startAppSettings() {
        isNeedCheck = true;
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    protected void permissionOK() {
        checkOK = true;
    }

//    private static final String TAG = "TAG";
//    @Override
//       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//               FragmentManager fm = getSupportFragmentManager();
//        int index = requestCode >> 16;
//              if (index != 0) {
//                      index--;
//                      if (fm.getFragments() == null || index < 0 || index >= fm.getFragments().size()) {
//                          Log.w(TAG, "Activity result fragment index out of range: 0x"
//                                  + Integer.toHexString(requestCode));
//                            return;
//                      }
//                       Fragment frag = fm.getFragments().get(index);
//                       if (frag == null) {
//                              Log.w(TAG, "Activity result no fragment exists for index: 0x"
//                                      + Integer.toHexString(requestCode));
//                           } else {
//                           handleResult(frag, requestCode, resultCode, data);
//                            }
//                        return;
//                   }
//    }


//    /**
//     38      * 递归调用，对所有子Fragement生效
//     39      *
//     40      * @param frag
//     41      * @param requestCode
//     42      * @param resultCode
//     43      * @param data
//     44      */
//      private void handleResult(Fragment frag, int requestCode, int resultCode,
//                                                           Intent data) {
//        frag.onActivityResult(requestCode & 0xffff, resultCode, data);
//        List<Fragment> frags = frag.getChildFragmentManager().getFragments();
//            if (frags != null) {
//                     for (Fragment f : frags) {
//                              if (f != null)
//                                     handleResult(f, requestCode, resultCode, data);
//                         }
//                  }
//          }
}
